package ui;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

import util.FileUtil;
import util.MathUtil;
import util.ModelToScriptUtil;

import app.JPGWriter;
import app.MConstants;
import app.MyFileFilter;

import com.wolfram.jlink.KernelLink;
import com.wolfram.jlink.MathGraphicsJPanel;


public class AnalysisResultPage extends Composite {
	
	private JPanel jGraphsPanel = null;
	static KernelLink ml;
	/**
	 * Create the composite
	 * @param parent
	 * @param style
	 */
	public AnalysisResultPage(Composite parent, int style) {
		super(parent, style);
		intitialMathematica();
		final ScrolledComposite scrolledComposite = new ScrolledComposite(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
		scrolledComposite.setBounds(0, 0, 604, 565);

		final Composite composite = new Composite(scrolledComposite, SWT.EMBEDDED);

		final Frame frame = SWT_AWT.new_Frame(composite);

		frame.add(getJGraphsPanel(), BorderLayout.CENTER);
		composite.setSize(604, 565);
		scrolledComposite.setContent(composite);

		final Button analysisButton = new Button(this, SWT.NONE);
		analysisButton.setText("analysis");
		analysisButton.setBounds(621, 137, 44, 23);
		analysisButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				analysis();
			}
		});
		
		final Button saveButton = new Button(this, SWT.NONE);
		saveButton.setText("save");
		saveButton.setBounds(621, 222, 44, 23);
		saveButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
//				save();
			}
		});

		final Button clearButton = new Button(this, SWT.NONE);
		clearButton.setText("clear");
		clearButton.setBounds(621, 312, 44, 23);

	}
	
	protected void save() {
		int result;
		JFileChooser saveFileChooseer = new JFileChooser("D://");
		saveFileChooseer.setApproveButtonText("OK");
		saveFileChooseer.setDialogTitle("Save Analysis Result");
		saveFileChooseer.addChoosableFileFilter(new MyFileFilter(".jpg",
				"jpg格式 (*.jpg)"));
		result = saveFileChooseer.showSaveDialog(jGraphsPanel);
		if (result == JFileChooser.APPROVE_OPTION) {
			File file = saveFileChooseer.getSelectedFile();
			MyFileFilter filter = (MyFileFilter) saveFileChooseer
					.getFileFilter();
			String ends = filter.getEnds();
			File newFile = null;
			if (file.getAbsolutePath().toUpperCase().endsWith(
					ends.toUpperCase())) {
				newFile = file;
			} else {
				newFile = new File(file.getAbsolutePath() + ends);
			}
			if (newFile != null) {
				JPGWriter writer = new JPGWriter(null);
				try {
					writer.write(getJGraphsPanel(), new FileOutputStream(
							newFile));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
				JOptionPane.showMessageDialog(null, "Save Success!",
						"Information", JOptionPane.INFORMATION_MESSAGE);
			}
		}

	}

	/**
	 * This method initializes jGraphsPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJGraphsPanel() {
		if (jGraphsPanel == null) {
			jGraphsPanel = new MathGraphicsJPanel(ml);
			jGraphsPanel.setLayout(new BorderLayout());
			jGraphsPanel.setBorder(BorderFactory
					.createTitledBorder(""));
		}
		return jGraphsPanel;
	}
	
	private void intitialMathematica() {
//		//如果没有设置Mathematica Kennerl，跳出
//		if(MConstants.MATHEMATICA_DEFAULT_TOOLTIP.equals(MConstants.MATH_KERNEL_PATH)) {
//			return;
//		}
		ml = MathUtil.getKernelLink();
//		this.addControlListener(new java.awt.event.WindowAdapter() {
//			public void windowClosing(java.awt.event.WindowEvent e) {
//				if (ml != null) {
//					// Because we used the front end, it is important
//					// to call CloseFrontEnd[] before closing the link.
//					// Counterintuitively, this is not because we want
//					// to force the front end to quit, but because we
//					// _don't_ want to do this if the user has begun
//					// working in the front end session we started.
//					// CloseFrontEnd knows how to politely disengage
//					// from the front end if necessary. The need for
//					// this will go away in future releases of
//					// Mathematica.
//					ml.evaluateToInputForm("CloseFrontEnd[]", 0);
//					ml.close();
//				}
//			}
//		});
	}
	
	protected void analysis() {
		//read model path from file
//		String mathScript = ModelToScriptUtil.getFrameworkModeAndProjectModelScript() + ";\n" +ModelToScriptUtil.getMethodModelScript();
//		System.out.println(mathScript);
		//operate mathematica kernel
		((MathGraphicsJPanel)getJGraphsPanel()).setImageType(
//				getJTypesetCheckBox().isSelected() ? MathGraphicsJPanel.TYPESET : MathGraphicsJPanel.GRAPHICS);
				false ? MathGraphicsJPanel.TYPESET : MathGraphicsJPanel.GRAPHICS);
//		((MathGraphicsJPanel) getJGraphsPanel())
//				.setMathCommand(mathScript.trim());
	}
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

}
